package com.murphy.algorithm.likou;

/**
 * 反转链表
 * @author dongsufeng
 * @version 4.0
 * @date 2023/2/20 18:03
 */
public class ReverseList {

    public ListNode reverse1(ListNode l){
        ListNode prev = null;
        ListNode curr = l;
        while (curr!=null){
            ListNode temp = curr.next;
            curr.next = prev;
            prev=curr;
            curr=temp;
        }
        return prev;
    }


    public ListNode reverse(ListNode l){
        ListNode newNode = null;
        while (l != null){
            ListNode temp = l.next;
            l.next = newNode;
            newNode = l;
            l = temp;
        }
        return newNode;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(3);
        l1.next = new ListNode(23);
        l1.next.next=new ListNode(9);
        l1.next.next.next=new ListNode(12);
        ReverseList list = new ReverseList();
        ListNode newnode = list.reverse(l1);
        while (newnode!=null){
            System.out.println(newnode.val);
            newnode = newnode.next;
        }
    }

    public static class ListNode{
        private int val;
        private ListNode next;
        public ListNode(){}
        public ListNode(int val){
            this.val = val;
        }
    }
}
